﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using umbraco.cms.businesslogic.datatype;
using System.Xml;
using System.ComponentModel;

namespace TheOutfield.UmbExt.UniversalMediaPicker
{
    public delegate void BeforeSaveEventHandler(object sender, BeforeSaveEventArgs e);
    public delegate void AfterSaveEventHandler(object sender, AfterSaveEventArgs e);

    public class UniversalMediaPickerData : DefaultData
    {
        public static event BeforeSaveEventHandler BeforeSave;
        public static event AfterSaveEventHandler AfterSave;

        public UniversalMediaPickerData(BaseDataType dataType)
            : base (dataType)
        { }

        public override System.Xml.XmlNode ToXMl(System.Xml.XmlDocument data)
        {
            if (this.Value != null && this.Value.ToString().Trim() != "") 
            { 
                var xd = new XmlDocument(); 
                xd.LoadXml(this.Value.ToString()); 
                return data.ImportNode(xd.DocumentElement, true); 
            } 

            return base.ToXMl(data); 
        }

        internal void InvokeBeforeSave(BeforeSaveEventArgs e)
        {
            BeforeSaveEventHandler handler = BeforeSave;
            if (handler != null) handler(this, e);
        }

        internal void InvokeAfterSave(AfterSaveEventArgs e)
        {
            AfterSaveEventHandler handler = AfterSave;
            if (handler != null) handler(this, e);
        }
    }

    public class BeforeSaveEventArgs : CancelEventArgs
    {
        public int DataTypeDefinitionId { get; set; }
        public string OldId { get; set; }
        public string NewId { get; set; }

        public BeforeSaveEventArgs(int dtdid, string oldId, string newId)
        {
            DataTypeDefinitionId = dtdid;
            OldId = oldId;
            NewId = newId;
        }
    }

    public class AfterSaveEventArgs : CancelEventArgs
    {
        public int DataTypeDefinitionId { get; set; }
        public string Id { get; set; }

        public AfterSaveEventArgs(int dtdid, string id)
        {
            DataTypeDefinitionId = dtdid;
            Id = id;
        }
    }
}